//
//  SetCookieViewController.m
//  WKWebViewDemo
//
//  Created by migu-hfy on 16/3/29.
//  Copyright © 2016年 migu-hfy. All rights reserved.
//

#import "SetCookieViewController.h"
#import <WebKit/WebKit.h>

@interface SetCookieViewController ()

@end

@implementation SetCookieViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setCookieInRequest];
    
    [self setCookieWhenDocumentStart];
}

- (void)setCookieInRequest
{
    //设置cookie到request的头部
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com/index.html"]];
    [request addValue:@"TeskCookieKey1=TeskCookieValue1;TeskCookieKey2=TeskCookieValue2;" forHTTPHeaderField:@"Cookie"];
}

- (void)setCookieWhenDocumentStart
{
    //当页面有Ajax请求时, 可以在文档开始的时候, 通过js设置cookie
    WKUserContentController* userContentController = WKUserContentController.new;
    WKUserScript * cookieScript = [[WKUserScript alloc]
                                   initWithSource: @"document.cookie = 'TeskCookieKey1=TeskCookieValue1';document.cookie = 'TeskCookieKey2=TeskCookieValue2';"
                                   injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    [userContentController addUserScript:cookieScript];
    WKWebViewConfiguration* webViewConfig = WKWebViewConfiguration.new;
    webViewConfig.userContentController = userContentController;
    
    WKWebView * webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:webViewConfig];
    [self.view addSubview:webView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
